package com.guapi.controller;

import com.google.code.kaptcha.Producer;
import com.guapi.entity.User;
import com.guapi.service.UserService;
import com.guapi.util.MallConstant;
import com.guapi.util.MallUtil;
import com.guapi.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements MallConstant {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage() {
        return "/site/login";
    }

    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response) {

        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入redis，验证码归属，最后丢进cookie里
        String kaptchaOwner = MallUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaowner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath+"/login");
        response.addCookie(cookie);

        //存入redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 120, TimeUnit.SECONDS);

        //输出图片
        response.setContentType("image/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败" + e.getMessage());
        }
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String loginUserName, String loginPassword, String code, boolean remember, Model model, @CookieValue("kaptchaowner") String kaptchaOwner,HttpServletResponse response) {
        String kaptcha = null;
        //从redis取出验证码
        if (StringUtils.isNoneBlank(kaptchaOwner)) {
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }

        //验证码判断
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确");
            return "/site/login";
        }

        //判断记住我状态
        int expireSeconds = remember ? REMEMBER_EXPIRE_SECOND : DEFAULT_EXPIRE_SECOND;

        Map<String, Object> map = userService.login(loginUserName, loginPassword, expireSeconds);
        if (map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            //cookie.setPath(contextPath);
            cookie.setMaxAge(expireSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        }else {
            model.addAttribute("loginUsernameMsg", map.get("loginUsernameMsg"));
            model.addAttribute("loginPasswordMsg", map.get("loginPasswordMsg"));
            return "/site/login";
        }

    }

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public String register(User user, Model model) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活");
            model.addAttribute("target", "/index");
            //返回注册的操作结果
            return "/site/operate-result";
        } else {

            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/login";

        }
    }

    @RequestMapping(path = "/activation/{userId}/{code}", method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        //判断验证结果
        int result = userService.activation(userId, code);
        if (result == USER_ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，用户已经能正常使用网站内的各种功能，请登录");
            model.addAttribute("target", "/login");
        } else if (result == USER_ACTIVATION_REPEAT) {
            model.addAttribute("msg", "重复激活，您的账户已经激活");
            model.addAttribute("target", "/login");
        } else {
            model.addAttribute("msg", "激活失败，您的激活码不正确");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    @RequestMapping(path = "/logout",method = RequestMethod.GET)
    public String logout(@CookieValue("ticket")String ticket){
        userService.logout(ticket);
        //SecurityContextHolder.clearContext();
        return "redirect:/login";
    }
}
